package com.dhecp.project.business.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.framework.util.ShiroUtils;
import com.dhecp.project.business.domain.ProductActive;
import com.dhecp.project.business.domain.ProductCarefullyChosen;
import com.dhecp.project.business.domain.ProductCarefullySetting;
import com.dhecp.project.business.domain.TysCart;
import com.dhecp.project.business.mapper.ProductActiveMapper;
import com.dhecp.project.business.mapper.ProductCarefullyChosenMapper;
import com.dhecp.project.business.mapper.ProductCarefullySettingMapper;
import com.dhecp.project.business.mapper.TysCartMapper;
import com.dhecp.project.business.service.ChoiceShopService;
import com.dhecp.project.common.domain.ModuleNidAndBid;
import com.dhecp.project.common.mapper.ModuleNidAndBidMapper;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.finance.domain.AccountCountForCompany;
import com.dhecp.project.finance.mapper.AccountCountForCompanyMapper;
import com.dhecp.project.flowable.domain.SysProcessInstance;
import com.dhecp.project.flowable.mapper.SysProcessInstanceMapper;
import com.dhecp.project.flowable.service.ActProcessService;
import com.dhecp.project.hr.domain.ChoiceShop;
import com.dhecp.project.hr.domain.OperateCompanyApply;
import com.dhecp.project.hr.domain.ProductSetup;
import com.dhecp.project.hr.mapper.ChoiceShopMapper;
import com.dhecp.project.hr.mapper.OperateCompanyApplyMapper;
import com.dhecp.project.hr.mapper.ProductSetupMapper;
import com.dhecp.project.purchase.domain.PurchaseAddress;
import com.dhecp.project.purchase.domain.PurchasePlan;
import com.dhecp.project.purchase.domain.PurchasePlanSon;
import com.dhecp.project.purchase.mapper.PurchaseAddressMapper;
import com.dhecp.project.purchase.mapper.PurchasePlanMapper;
import com.dhecp.project.purchase.mapper.PurchasePlanSonMapper;
import com.dhecp.project.storage.domain.StockAllot;
import com.dhecp.project.storage.domain.StockControl;
import com.dhecp.project.storage.mapper.StockAllotMapper;
import com.dhecp.project.storage.mapper.StockControlMapper;
import com.dhecp.project.system.domain.SysUserInfo;

/**
 * @program: kjecp
 * @description: 逸思精品
 * @author: hlf
 * @create: 2022-12-13 14:51
 */
@Service
public class ChoiceShopServiceImpl extends BaseModuleServiceImpl implements ChoiceShopService {

    @Autowired
    private ChoiceShopMapper choiceShopMapper;
    @Autowired
    private StockControlMapper stockControlMapper;
    @Autowired
    private OperateCompanyApplyMapper operateCompanyApplyMapper;
    @Autowired
    private StockAllotMapper stockAllotMapper;
    @Autowired
    private PurchasePlanMapper purchasePlanMapper;
    @Autowired
    private PurchasePlanSonMapper purchasePlanSonMapper;
    @Autowired
    private PurchaseAddressMapper purchaseAddressMapper;
    @Autowired
    private ModuleNidAndBidMapper moduleNidAndBidMapper;
    @Autowired
    private AccountCountForCompanyMapper accountCountForCompanyMapper;
    @Autowired
    private ProductActiveMapper productActiveMapper;

    @Autowired
    private ActProcessService actProcessService;

    @Autowired
    private SysProcessInstanceMapper processInstanceMapper;

    @Autowired
    private ProductCarefullyChosenMapper productCarefullyChosenMapper;
    @Autowired
    private ProductCarefullySettingMapper productCarefullySettingMapper;
    @Autowired
    private ProductSetupMapper productSetupMapper;
    @Autowired
    private TysCartMapper tysCartMapper;


    /**
     * @Description: 查询商品列表
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.business.domain.ProductActive>
     * @Author: hlf
     * @date: 2022-12-13 14:55
     */
    @Override
    public List<ChoiceShop> queryProductActive(Map<String, Object> params) throws Exception {
        if (params.get("field") == null || params.get("field") == "") {
            String orderBy = "t1.UpdateTime desc";
            PageUtils.startPageOrder(orderBy);
        } else {
            PageUtils.startPage();
        }
        return choiceShopMapper.selectChoiceShop(params);
    }

    /**
     * @Description: 查询商品列表
     * @Param: [params]
     * @return: java.util.List<com.dhecp.project.business.domain.ProductActive>
     * @Author: hlf
     * @date: 2022-12-13 14:55
     */
    @Override
    public List<StockAllot> allotList(Map<String, Object> params) throws Exception {
        return stockAllotMapper.allotList(params.get("code").toString(), ShiroUtils.getUserId());
    }


    /**
     * @Description: 保存商品设置
     * @Param: [params]
     * @return: com.dhecp.common.core.domain.AjaxResult
     * @Author: hlf
     * @date: 2022-12-14 9:49
     */
    @Override
    public AjaxResult commodityAllocation(Map<String, Object> params) {
        List<ChoiceShopData> choiceShop = JSON.parseArray(params.get("choiceShop").toString(), ChoiceShopData.class);
        OperateCompanyApply corporate = JSON.parseObject(params.get("corporate").toString(), OperateCompanyApply.class);
        
        // 调拨总价求和
        Double totalPriceAll = 0D;
        for(ChoiceShopData choiceShopData : choiceShop) {
        	totalPriceAll = totalPriceAll + choiceShopData.getTotalPrice();
        }

        AjaxResult ajaxResult = AjaxResult.success();

        //判断调拨人资金是否充足 FJe+FFzEd-FDjJe
        AccountCountForCompany accountCountForCompany = accountCountForCompanyMapper.queryFirstByVGsBm(corporate.getvGsBm());
        if (accountCountForCompany == null ) return AjaxResult.error("用户未绑定有效的资金账号!");
        else if (!(accountCountForCompany.getfJe() + accountCountForCompany.getfFzEd() - accountCountForCompany.getfDjJe() > totalPriceAll)) {
            return AjaxResult.error("用户可用资金不足!");
        }

        for (ChoiceShopData item : choiceShop) {
        	item.setCode(item.getProductCode());
        	item.setName(item.getProductName());
            Integer allot = item.getNumAllot();//调拨总数

            // 调货信息所在仓库
            String warehouse = item.getWarehouse();

            //获取商品信息
            ProductActive productActive = productActiveMapper.findProductActiveByCode(item.code);
            item.setName(productActive.getName());
            //获取商品库存
            List<StockControl> stockControls = stockControlMapper.findByCode3(item.getCode(), "GS0641", warehouse);//固定公司 逸思精品
            //获取所属公司信息
            OperateCompanyApply corporate2 = operateCompanyApplyMapper.findVGsBm("GS0641");
            if (stockControls.size() > 0) {//有可用库存的情况 直接调拨库存
                for (StockControl item2 : stockControls) {
                    if (allot > 0 && item2.getProductNum() > 0) {
                        ajaxResult = createStockAllot(item, item2, allot, corporate);
                        allot = (Integer) ajaxResult.get("data");
                        if (allot < 0){
                            return AjaxResult.error("用户可用资金不足！");
                        }
                    }
                }
            }
            if (allot > 0) {//库存不够调拨的情况 生成 调拨单
                ajaxResult = createStockAllot2(item, allot, corporate, corporate2, warehouse);
            }
        }

        return ajaxResult;
    }

    //生成调拨单
    public AjaxResult createStockAllot(ChoiceShopData choiceShop, StockControl stockControl, Integer allot, OperateCompanyApply corporate) {
        StockAllot stockAllot = new StockAllot();
        Map<String, Object> params = new HashMap<>();
        int x = 0;
        int y = 0;
        //调拨数量计算
        if (allot > stockControl.getProductNum()) {
            x = stockControl.getProductNum();
            y = allot - stockControl.getProductNum();
        } else {
            x = allot;
            y = 0;
        }

        params.put("moduleTable", "TCC_STOCKALLOT");
        ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params);    //有事务控制，制单异常不跳过单号
        //生成调拨单
        //基础信息
        stockAllot.setNid(moduleNidAndBid.getNid());
        stockAllot.setBid(moduleNidAndBid.getBid());
        stockAllot.setCreateTime(new Date());
        stockAllot.setUpdateTime(new Date());
        stockAllot.setCid(ShiroUtils.getMandatorCid());
        stockAllot.setCidName(ShiroUtils.getMandatorCidName());
        stockAllot.setbUser(ShiroUtils.getMandatorId());
        stockAllot.setbUserName(ShiroUtils.getMandatorName());
        stockAllot.setbDept(ShiroUtils.getMandatorDeptPath());
        stockAllot.setbDeptName(ShiroUtils.getMandatorDeptName());
        stockAllot.setbPosition(ShiroUtils.getMandatorPositionNameDa());
        stockAllot.setaUser(ShiroUtils.getUserId());
        stockAllot.setaUserName(ShiroUtils.getUserName());
        stockAllot.setaDept(ShiroUtils.getUserDeptPath());
        stockAllot.setaDeptName(ShiroUtils.getUserDeptName());
        stockAllot.setaPosition(ShiroUtils.getUserPositionNameDa());
        stockAllot.setEffectStock(true);//是否生效
        stockAllot.setDeleted(false);//是否删除
        stockAllot.setActiveFlow("end");//流程状态
        stockAllot.setvZdbz("逸思精品调拨");//单据备注
        stockAllot.setvBz("0");//单据备注
        //调拨信息
        stockAllot.setProductName(choiceShop.getName());//商品名称
        stockAllot.setProductCode(choiceShop.getCode());//商品编码
        stockAllot.setProductNum(stockControl.getProductNum());//商品数量
        stockAllot.setPrice(choiceShop.getRealPrice());//调拨单价
        stockAllot.setTotalPrice(choiceShop.getTotalPrice());//调拨总价
        stockAllot.setGoodsAllocation(stockControl.getvHw());//货位编码
        stockAllot.setGoodsArea(stockControl.getvKq());//库区
        stockAllot.setWarehouseAddress(stockControl.getgDepot());//所在仓库
        stockAllot.setvGsBm(stockControl.getvGsBm());//所属公司编码
        stockAllot.setvGsMc(stockControl.getvGsMc());//所属公司名称
        stockAllot.setvGsJc(stockControl.getvGsJc());//所属公司简称
        stockAllot.setpGuid(stockControl.getRkGuid());//RKGUID

        stockAllot.setAllotNum(x);//调拨数量
        stockAllot.setAllotSum(x * choiceShop.getRealPrice());//调拨金额
        stockAllot.setToGoodsAllocation(stockControl.getvHw());//调入货区
        stockAllot.setToGoodsArea(stockControl.getvKq());//调入库区
        stockAllot.setToWarehouseAddress(stockControl.getgDepot());//调入仓库
        stockAllot.setToGCName(corporate.getvGsMc());//调入公司名称
        stockAllot.setToGClient(corporate.getvGsBm());//调入公司编码

        stockAllotMapper.insert(stockAllot);//生成调拨信息

        // 删除购物车
        tysCartMapper.delete(choiceShop.getId());
        return AjaxResult.success("操作成功!",y);
    }


    //生成调拨单(无库存情况)
    public AjaxResult createStockAllot2(ChoiceShopData choiceShop, Integer allot, OperateCompanyApply corporate, OperateCompanyApply corporate2, String warehouse) {
        String moduleTable = "TCC_STOCKALLOT";
        String moduleName = "库存调拨单";
        StockAllot stockAllot = new StockAllot();
        Map<String, Object> params = new HashMap<>();

        params.put("moduleTable", "TCC_STOCKALLOT");
        ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params);    //有事务控制，制单异常不跳过单号
        //生成调拨单
        //基础信息
        stockAllot.setNid(moduleNidAndBid.getNid());
        stockAllot.setBid(moduleNidAndBid.getBid());
        stockAllot.setCreateTime(new Date());
        stockAllot.setCid(ShiroUtils.getMandatorCid());
        stockAllot.setCidName(ShiroUtils.getMandatorCidName());
        stockAllot.setbUser(ShiroUtils.getMandatorId());
        stockAllot.setbUserName(ShiroUtils.getMandatorName());
        stockAllot.setbDept(ShiroUtils.getMandatorDeptPath());
        stockAllot.setbDeptName(ShiroUtils.getMandatorDeptName());
        stockAllot.setbPosition(ShiroUtils.getMandatorPositionNameDa());
        stockAllot.setaUser(ShiroUtils.getUserId());
        stockAllot.setaUserName(ShiroUtils.getUserName());
        stockAllot.setaDept(ShiroUtils.getUserDeptPath());
        stockAllot.setaDeptName(ShiroUtils.getUserDeptName());
        stockAllot.setaPosition(ShiroUtils.getUserPositionNameDa());
        stockAllot.setEffectStock(false);//是否生效
        stockAllot.setDeleted(false);//是否删除
        stockAllot.setActiveFlow("FlowZd");//流程状态
        stockAllot.setvZdbz("逸思精品调拨");//单据备注
        stockAllot.setvBz("1");//单据备注
        //调拨信息
        stockAllot.setProductName(choiceShop.getName());//商品名称
        stockAllot.setProductCode(choiceShop.getCode());//商品编码
        stockAllot.setProductNum(0);//商品数量
        stockAllot.setPrice(choiceShop.getRealPrice());//调拨单价
        stockAllot.setTotalPrice(choiceShop.getTotalPrice());//调拨总价
        stockAllot.setGoodsAllocation("精品1区");//货位编码
        stockAllot.setGoodsArea("精品区");//库区
        stockAllot.setWarehouseAddress(warehouse);//所在仓库
        stockAllot.setAllotNum(allot);//调拨数量
        stockAllot.setAllotSum(allot * choiceShop.getRealPrice());//调拨金额
        stockAllot.setToGoodsAllocation("精品1区");//调入货位编码
        stockAllot.setToGoodsArea("精品区");//调入库区
        stockAllot.setToWarehouseAddress(warehouse);//调入仓库
        stockAllot.setToGCName(corporate.getvGsMc());//调入公司名称
        stockAllot.setToGClient(corporate.getvGsBm());//调入公司编码
        stockAllot.setvGsJc(corporate2.getvGsJc());//所属公司简称
        stockAllot.setvGsMc(corporate2.getvGsMc());//所属公司名称
        stockAllot.setvGsBm(corporate2.getvGsBm());//所属公司编码


        //生成流程信息
        AjaxResult ajaxResult = AjaxResult.success();
        SysProcessInstance sysProcessInstance = new SysProcessInstance();
        String processTitle = moduleName + "(" + moduleNidAndBid.getBid() + ")";
        String procDefKey = moduleTable;
        String tableDataId = moduleNidAndBid.getNid().toString();
        sysProcessInstance.setProcessTitle(processTitle);
        sysProcessInstance.setProcDefKey(procDefKey);
        sysProcessInstance.setTableDataId(tableDataId);
        sysProcessInstance.setProcessRemark("备注:逸思精品调拨");
        sysProcessInstance.setCorpNo(ShiroUtils.getMandatorCid());
        sysProcessInstance.setCorpName(ShiroUtils.getMandatorCidName());
        ajaxResult = actProcessService.startProcess(sysProcessInstance);
        if ("0".equals(ajaxResult.get("code").toString())) {
            if ("flowzd".equals(sysProcessInstance.getNextActAlias().toString().toLowerCase())) {
                //插入指定单据流转各环节审批人记录
                Map<String, Object> flowRecord = new HashMap<String, Object>();
                flowRecord.put("moduleTable", moduleTable);
                flowRecord.put("nid", tableDataId);
                flowRecord.put("activeFlowOld", sysProcessInstance.getNextActAlias());
                flowRecord.put("activeFlow", sysProcessInstance.getNextActAlias());
                flowRecord.put("activeFlowName", sysProcessInstance.getNextActAlias());
                flowRecord.put("procInstId", sysProcessInstance.getProcInstId());
                flowRecord.put("createUser", ShiroUtils.getMandatorId());
                flowRecord.put("createUserName", ShiroUtils.getMandatorName());
                flowRecord.put("updateUsers", ShiroUtils.getMandatorId());
                flowRecord.put("optType", "add");
                processInstanceMapper.insertProcessInstanceFlowRecord(flowRecord);
            } else {
                throw new RuntimeException(MessageUtils.message("flowable.model.error.modelflowzdfail"));
            }
        }
        stockAllot.setProcInstId(sysProcessInstance.getProcInstId());
        stockAllotMapper.insert(stockAllot);//生成调拨信息

        // 删除购物车
        tysCartMapper.delete(choiceShop.getId());

        return AjaxResult.success("操作成功，已生成调拨单请及时流转!");
    }

    //生成采购计划
    public void createPurchasePlan(ChoiceShop choiceShop, Integer allot, OperateCompanyApply corporate) {
        PurchasePlan plan = new PurchasePlan();
        Map<String, Object> params = new HashMap<>();
        params.put("moduleTable", "TCG_PURCHASEPLAN");
        //有事务控制，制单异常不跳过单号
        ModuleNidAndBid moduleNidAndBid = moduleNidAndBidMapper.findModuleNidAndBid(params);
        PurchaseAddress purchaseAddress = purchaseAddressMapper.getTop1();
        try {
            //生成采购计划 母件 信息
            //基础信息
            plan.setNid(moduleNidAndBid.getNid());
            plan.setBid(moduleNidAndBid.getBid());
            plan.setCreateTime(new Date());
            plan.setCid(ShiroUtils.getMandatorCid());
            plan.setCidName(ShiroUtils.getMandatorCidName());
            plan.setbUser(ShiroUtils.getMandatorId());
            plan.setbUserName(ShiroUtils.getMandatorName());
            plan.setbDept(ShiroUtils.getMandatorDeptPath());
            plan.setbDeptName(ShiroUtils.getMandatorDeptName());
            plan.setbPosition(ShiroUtils.getMandatorPositionNameDa());
            plan.setaUser(ShiroUtils.getUserId());
            plan.setaUserName(ShiroUtils.getUserName());
            plan.setaDept(ShiroUtils.getUserDeptPath());
            plan.setaDeptName(ShiroUtils.getUserDeptName());
            plan.setaPosition(ShiroUtils.getUserPositionNameDa());
            plan.setvGsDz(purchaseAddress.getAddress());//获取默认地址
            plan.setAddressId(purchaseAddress.getGuid());//地址标识
            plan.setEffectStock(true);//是否生效
            plan.setDeleted(false);//是否删除
            plan.setActiveFlow("end");//流程状态
            plan.setvZdbz("逸思精品调拨");//单据备注

            //母件信息
            plan.setSpBm(choiceShop.getCode());//商品编码
            plan.setSpSl(allot);//商品编码
            plan.setvType(2);//商品编码
            plan.setSort("线下");//类型 (线上/线下
            plan.setIsJp("是");//类型 (线上/线下
//            plan.setOrderState("订单已生成");//订单状态 (订单已生成/空/订单已删除
            plan.setvGsBm(corporate.getvGsBm());
            plan.setvGsJc(corporate.getvGsJc());
            plan.setvGsMc(corporate.getvGsMc());

            //订单地址
            Map<String, Object> address = new HashMap<String, Object>();
            address.put("guid", plan.getAddressId());
            PurchaseAddress purchaseAddress2 = purchaseAddressMapper.findById(address);
            if (purchaseAddress2 != null) {
                plan.setPhone(purchaseAddress2.getPhone());//联系电话
                plan.setvBank(purchaseAddress2.getvBank());//开户行
                plan.setvAccount(purchaseAddress2.getvAccount());//银行账号
                plan.setvTax(purchaseAddress2.getvTax());//税号
                plan.setvJydz(purchaseAddress2.getvJydz());//经营地址
                plan.setvKpdh(purchaseAddress2.getvKpdh());//开票电话
                plan.setvKpdz(purchaseAddress2.getvKpdz());//开票地址
                plan.setvGsfr(purchaseAddress2.getvGsfr());//公司法人
                plan.setvLxdh(purchaseAddress2.getvLxdh());//联系电话
                plan.setvFax(purchaseAddress2.getvFax());//传真
                plan.setvGjH(purchaseAddress2.getvGjH());//所在国家
                plan.setvSfH(purchaseAddress2.getvSfH());//省份
                plan.setvDsH(purchaseAddress2.getvDsH());//城市
                plan.setvCqH(purchaseAddress2.getvCqH());//城区
                plan.setvDzH(purchaseAddress2.getvDzH());//街道
                plan.setvYbH(purchaseAddress2.getvYbH());//邮编
                plan.setvFhr(purchaseAddress2.getvFhr());//发货人
                plan.setvFhrSj(purchaseAddress2.getvFhrSj());//发货人手机
                plan.setvFhrDh(purchaseAddress2.getvFhrDh());//发货人电话
                plan.setvGjP(purchaseAddress2.getvGjP());//国家 票
                plan.setvSfP(purchaseAddress2.getvSfP());//省份 票
                plan.setvDsP(purchaseAddress2.getvDsP());//城市 票
                plan.setvCqP(purchaseAddress2.getvCqP());//城区 票
                plan.setvDzP(purchaseAddress2.getvDzP());//地址 票
                plan.setvYbP(purchaseAddress2.getvYbP());//邮编 票
                plan.setvSpr(purchaseAddress2.getvSpr());//收票人
                plan.setvSprSj(purchaseAddress2.getvSprSj());//收票人手机
                plan.setvSprDh(purchaseAddress2.getvSprDh());//收票人电话
                plan.setInvoiceType(purchaseAddress2.getInvoiceType());//发票类型
            }
            //生成子件数据
            List<PurchasePlanSon> sonList = purchasePlanSonMapper.queryListFbm(plan.getSpBm());
            Integer xb = 0;
            for (PurchasePlanSon item : sonList
            ) {
                if (item.getfBm().equals(plan.getSpBm())) {
                    xb++;
                    item.setGuid(RandomValueUtils.getGUID());
                    item.setCreateTime(new Date());
                    item.setfNid(plan.getNid());
                    item.setfBm(plan.getSpBm());//父商品编码
                    item.setCgSl((int) Math.round(allot * item.getNum()));//母件计划子件采购数量
                    item.setJgSl(0);//子件加购数量
//                    item.setPrices(choiceShop.getPurchasePrice());//子件预估单价
                    item.setTotalPrices(item.getPrices() * item.getNum());//子件预估总价
                    item.setAllNum((int) Math.round(allot * item.getNum()));//子件总数
                    item.setpGuid(plan.getGuid());//父标识
                    item.setIid(xb);//行号
//                    cost = cost + item.getTotalPrices();
                    purchasePlanSonMapper.insert(item);
                }

            }
            plan.setPlanCost(choiceShop.getTotalPrice());
            plan.setUpdateTime(new Date());
            purchasePlanMapper.insert(plan);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public AjaxResult editDetailBatch(String pcode, String detailArr) {
    	
    	if (pcode == null || pcode.length() == 0) {
            return AjaxResult.error("提交的参数有误，请联系客服");
		}
    	
        JSONArray detailJA = JSON.parseArray(detailArr);

        // 验证数据是否已存在
        List<String> listUnicode = new ArrayList<String>();
        for (int i = 0; i < detailJA.size(); i++) {
            JSONObject detailJO = detailJA.getJSONObject(i);
            String code = detailJO.getString("code");
            String warehouse = detailJO.getString("warehouse");
            
            String unicode = code + pcode + warehouse;
            if (listUnicode.contains(unicode)) {
                return AjaxResult.error("存在重复的商品编码和仓库");
			} else {
				listUnicode.add(unicode);
			}
            
            ProductCarefullyChosen productCarefullyChosen = productCarefullyChosenMapper.findByCode(code);
            if (productCarefullyChosen == null) {
                return AjaxResult.error("该商品不存在于精品库");
            }
        }
        
        // 删除旧数据
        productCarefullySettingMapper.deleteBatchByPcode(pcode);
        Date now = new Date();
        // 添加调货信息
        String productID = null;
        BigDecimal originPriceMin = BigDecimal.ZERO;
        BigDecimal originPriceMax = BigDecimal.ZERO;
        for (int i = 0; i < detailJA.size(); i++) {

            JSONObject detailJO = detailJA.getJSONObject(i);

            String code = detailJO.getString("code");
            String attr = detailJO.getString("attr");
            String warehouse = detailJO.getString("warehouse");
            String size = detailJO.getString("size");
            String weight = detailJO.getString("weight");
            String unitName = detailJO.getString("unitName");
            Integer period = detailJO.getInteger("period");
            BigDecimal retailPrice = detailJO.getBigDecimal("retailPrice");
            BigDecimal originPrice = detailJO.getBigDecimal("originPrice");
            Integer numPerBox = detailJO.getInteger("numPerBox");
            Integer numBuyMin = detailJO.getInteger("numBuyMin");
            Integer numBuyMinSecond = detailJO.getInteger("numBuyMinSecond");
            Integer numAll = detailJO.getInteger("numAll");
            Integer numPreBuy = detailJO.getInteger("numPreBuy");
            String timeArrivePredict = detailJO.getString("timeArrivePredict");

            ProductCarefullySetting entity = new ProductCarefullySetting();
            entity.setGuid(RandomValueUtils.getGUID());
            entity.setCode(code);
            entity.setPcode(pcode);
            entity.setWarehouse(warehouse);
            entity.setSize(size);
            entity.setWeight(weight);
            entity.setUnitName(unitName);
            entity.setAttr(attr);
            entity.setRetailPrice(retailPrice);
            entity.setOriginPrice(originPrice);
            entity.setNumPerBox(numPerBox);
            entity.setNumBuyMin(numBuyMin);
            entity.setNumBuyMinSecond(numBuyMinSecond);
            entity.setPeriod(period);
            entity.setTimeArrivePredict(timeArrivePredict);
            entity.setNumAll(numAll);
            entity.setNumPreBuy(numPreBuy);
            entity.setStatus(1);
            entity.setCreateTime(now);
            entity.setUpdateTime(now);
            productCarefullySettingMapper.insert(entity);

            // 处理最小和最大金额
            if (i == 0) {
                originPriceMin = originPrice;
                originPriceMax = originPrice;
            }
            originPriceMin = originPriceMin.compareTo(originPrice) <= 0 ? originPriceMin : originPrice;
            originPriceMax = originPriceMax.compareTo(originPrice) >= 0 ? originPriceMax : originPrice;
            productID = pcode;
        }

        String originPriceRange = originPriceMin.toString();
        if (originPriceMin.compareTo(originPriceMax) != 0) {
            originPriceRange = originPriceMin + "~" + originPriceMax;
        }

        ProductSetup productSetup = productSetupMapper.findByCode(productID);
        productSetup.setOriginPriceRange(originPriceRange);
        productSetupMapper.update(productSetup);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult deleteDetail(String guid) {

        if (guid == null) {
            return AjaxResult.error("ID不能为空");
        }

        productCarefullySettingMapper.deleteByGuid(guid);

        return AjaxResult.success();
    }

    public static class ChoiceShopData {
    	private Long id; // 购物车ID
        private Integer numAllot;//调拨总数
        private String code;//编码
        private String name;//商品名称
        private String productCode;
        private String productName;
        private String warehouse;// 商品所在仓库
        private Double totalPrice; // 调拨总价
        private Double realPrice; // 调拨单价
		public Long getId() {
			return id;
		}
		public void setId(Long id) {
			this.id = id;
		}
		public Integer getNumAllot() {
			return numAllot;
		}
		public void setNumAllot(Integer numAllot) {
			this.numAllot = numAllot;
		}
		public String getCode() {
			return code;
		}
		public void setCode(String code) {
			this.code = code;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getProductCode() {
			return productCode;
		}
		public void setProductCode(String productCode) {
			this.productCode = productCode;
		}
		public String getProductName() {
			return productName;
		}
		public void setProductName(String productName) {
			this.productName = productName;
		}
		public String getWarehouse() {
			return warehouse;
		}
		public void setWarehouse(String warehouse) {
			this.warehouse = warehouse;
		}
		public Double getTotalPrice() {
			return totalPrice;
		}
		public void setTotalPrice(Double totalPrice) {
			this.totalPrice = totalPrice;
		}
		public Double getRealPrice() {
			return realPrice;
		}
		public void setRealPrice(Double realPrice) {
			this.realPrice = realPrice;
		}
    }


	@Override
	public AjaxResult addToCart(String choiceShop) {
		
		SysUserInfo loginUser = ShiroUtils.getSysUser();
		
		JSONArray choiceShopJA = JSON.parseArray(choiceShop);
		for (int i = 0; i < choiceShopJA.size(); i++) {
			JSONObject JO = choiceShopJA.getJSONObject(i);
			String productCode = JO.getString("code");
			ProductActive productActive = productActiveMapper.findProductActiveByCode(productCode);
			Long idSetting = JO.getLong("id");
			ProductCarefullySetting productCarefullySetting = productCarefullySettingMapper.findById(idSetting);

			// 箱数为0，直接跳过
			Integer numBox = JO.getInteger("numBox");
			if (numBox == null || numBox <= 0) {
				continue;
			}
			
			TysCart entity = tysCartMapper.findByIdSettingAndCreateUserId(idSetting, loginUser.getUserId());
			if (entity != null) {
				entity.setNumBox(entity.getNumBox() + numBox);
				entity.setNumAllot(entity.getNumBox()* entity.getNumPerBox());
				entity.setTotalPrice(entity.getOriginPrice().multiply(new BigDecimal(entity.getNumAllot())));
				tysCartMapper.update(entity);
			} else {
				entity = new TysCart();
				entity.setIdSetting(idSetting);
				entity.setProductCode(productCode);
				entity.setProductName(productActive.getName());
				entity.setNumBuyMin(productCarefullySetting.getNumBuyMin());
				entity.setNumPerBox(productCarefullySetting.getNumPerBox());
				
				entity.setNumBox(numBox);
				Integer numAllot = numBox * productCarefullySetting.getNumPerBox();
				entity.setNumAllot(numAllot);
				entity.setOriginPrice(productCarefullySetting.getOriginPrice());
				entity.setTotalPrice(productCarefullySetting.getOriginPrice().multiply(new BigDecimal(numAllot)));
				entity.setCreateUserId(loginUser.getUserId());
				entity.setCreateUserName(loginUser.getUserName());
				entity.setStatus(1);
				tysCartMapper.insert(entity);
			}
		}
		
		Object data = tysCartMapper.countByCreateUserId(loginUser.getUserId());
		return AjaxResult.success("操作成功", data);
	}

	@Override
	public AjaxResult removeFromCart(Long id) {
		tysCartMapper.delete(id);
		
		return AjaxResult.success("操作成功");
	}
}


